﻿using System;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Net;
using System.IO;
using Microsoft.Win32;

namespace BingWallpaper
{
    internal class WallpaperClass
    {
        public string InfoLink { get; }
        public string SavePath { get; }
        public string ImgPath { get; private set; }
        public string UrlLink { get; private set; }
        public string Copyright { get; private set; }
        public string CopyrightLink { get; private set; }
        public string ImgDate { get; private set; }

        #region API

        /// <summary>
        /// 调用 API 设置壁纸
        /// </summary>
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni);

        #endregion

        public WallpaperClass(string infoLink, string savePath)
        {
            InfoLink = infoLink;
            SavePath = savePath;
        }

        /// <summary>
        /// 获取壁纸数据后下载并应用壁纸
        /// </summary>
        public async Task GetInfo(bool isSet)
        {
            var webClient = new WebClient {Encoding = Encoding.UTF8};
            var strInfo = await webClient.DownloadStringTaskAsync(InfoLink);

            // 获取 UrlBase
            var intTop = strInfo.IndexOf("<urlBase>", StringComparison.Ordinal) + "<urlBase>".Length;
            var intEnd = strInfo.IndexOf("</urlBase>", StringComparison.Ordinal);
            UrlLink = $"https://www.bing.com{strInfo.Substring(intTop, intEnd - intTop)}_1920x1080.jpg";

            // 获取 Copyright
            intTop = strInfo.IndexOf("<copyright>", StringComparison.Ordinal) + "<copyright>".Length;
            intEnd = strInfo.IndexOf("</copyright>", StringComparison.Ordinal);
            Copyright = strInfo.Substring(intTop, intEnd - intTop);

            // 获取 CopyrightLink
            intTop = strInfo.IndexOf("<copyrightlink>", StringComparison.Ordinal) + "<copyrightlink>".Length;
            intEnd = strInfo.IndexOf("</copyrightlink>", StringComparison.Ordinal);
            CopyrightLink = strInfo.Substring(intTop, intEnd - intTop);

            // 获取 ImgDate
            intTop = strInfo.IndexOf("<enddate>", StringComparison.Ordinal) + "<enddate>".Length;
            intEnd = strInfo.IndexOf("</enddate>", StringComparison.Ordinal);
            ImgDate = strInfo.Substring(intTop, intEnd - intTop);

            // 设置壁纸路径
            ImgPath = $@"{SavePath}\{ImgDate}_1920x1080.jpg";

            DownloadFile();

            if (!isSet) return;

            SetWallpaper();
        }

        /// <summary>
        /// 下载壁纸
        /// </summary>
        private void DownloadFile()
        {
            // 创建壁纸目录
            Directory.CreateDirectory(SavePath);
            if (File.Exists(ImgPath)) return;
            using (var webClient = new WebClient())
                webClient.DownloadFile(UrlLink, ImgPath);
        }

        /// <summary>
        /// 应用壁纸
        /// </summary>
        private void SetWallpaper()
        {
            try
            {
                var wallpaper = Registry.CurrentUser.CreateSubKey(@"Control Panel\Desktop");
                if (wallpaper?.GetValue("Wallpaper") as string != ImgPath)
                {
                    wallpaper?.SetValue("Wallpaper", ImgPath);
                    wallpaper?.Close();
                }
                SystemParametersInfo(20, 0, ImgPath, 0x2);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
        }

    }
}
